const axios = require("axios");
const fs = require("fs");
const env = require("dotenv").config();
const { mkdirpSync } = require("./utils");
const path = require("path");

const { fy_client_id, fy_client_secret, fy_grant_type } = env.parsed;
/** 请求封装 */
async function getToken() {
  const { data } = await axios({
    url: "https://aip.baidubce.com/oauth/2.0/token",
    method: "post",
    headers: {
      "Content-Type": "application/json",
    },
    data: {},
    params: {
      client_id: fy_client_id,
      client_secret: fy_client_secret,
      grant_type: fy_grant_type,
    },
  });
  return data;
}

const main = async () => {
  const catchDir = path.join(process.cwd(), ".catch");
  mkdirpSync(catchDir);
  const data = await getToken();
  if (data.access_token) {
    console.log("token 更新成功");
    fs.writeFileSync(
      path.join(catchDir, "./fy-token"),
      JSON.stringify({
        token: data.access_token,
        expire: parseInt(new Date().getTime() / 1000) * 1 + data.expires_in,
      })
    );
    return data.access_token;
  } else {
    console.log("token 更新失败");
    return "";
  }
};

module.exports = main;
